/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.spi.support;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import net.datajanitor.baja.spi.BuilderException;

public class UrlBuilder {
    private static final String DEFAULT_HOST = "www.box.net";
    
    private String protocol = "http";
    private String host = DEFAULT_HOST;
    private int port = 80;
    private String path;
    private Map<String, String> params;
    
    public UrlBuilder setProtocol(String protocol) {
        this.protocol = protocol;
        return this;
    }

    public UrlBuilder setPort(int port) {
        this.port = port;
        return this;
    }

    public UrlBuilder setHost(String host) {
        this.host = host;
        return this;
    }

    public UrlBuilder setPath(String path) {
        this.path = path;
        return this;
    }

    public UrlBuilder setParams(Map<String, String> params) {
        this.params = params;
        return this;
    }
    
    public UrlBuilder addParam(String key, int value) {
        return addParam(key, String.valueOf(value));
    }

    public UrlBuilder addParam(String key, String value) {
        if (this.params == null) {
            this.params = new HashMap<String, String>();
        }
        this.params.put(key, value);
        return this;
    }

    public URL build() throws BuilderException {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(this.protocol).append("://").append(this.host);
            if (this.port != 80) {
                builder.append(":").append(this.port);
            }
            
            builder.append("/").append(this.path);
            if (this.params != null && !this.params.isEmpty()) {
                String sep = "?";
                for (Map.Entry<String, String> entry : this.params.entrySet()) {
                    builder.append(sep);
                    builder.append(entry.getKey()).append("=").append(entry.getValue());
                    
                    if ("?".equals(sep)) {
                        sep = "&";
                    }
                }
            }

            return new URL(builder.toString());
        } catch (MalformedURLException e) {
            throw new BuilderException("Error building URL", e);
        }
    }
}